from django.db import models
from datetime import datetime

from django.utils.html import format_html

from apps.users.models import WeChatUser
# Create your models here.

class BaseModel(models.Model):
    # now后不能加括号，否则会在系统编译的时候就调用这个函数，导致时间和实际不符
    add_time = models.DateTimeField(default=datetime.now, verbose_name="添加时间")

    class Meta:
        abstract = True

# Create your models here.
class TopicTag(BaseModel):
    tag = models.CharField(max_length=10, verbose_name=u'分类')

    class Meta:
        verbose_name = "话题分类"
        verbose_name_plural = verbose_name
    def __str__(self):
        return self.tag
    def message_nums(self):
        return self.topic_set.all().count()

# 话题
class Topic(BaseModel):
    author = models.ForeignKey(WeChatUser, on_delete=models.CASCADE, verbose_name="作者")
    title = models.CharField(max_length=50, verbose_name="标题")
    text = models.CharField(max_length=200, verbose_name="内容")
    likenum = models.IntegerField(default=0, verbose_name='点赞数')
    commentnum = models.IntegerField(default=0, verbose_name='评论数')
    tag = models.ForeignKey(TopicTag,on_delete=models.CASCADE, verbose_name="分类",default=1)
    is_show = models.BooleanField(default=False,verbose_name="是否显示")
    class Meta:
        verbose_name = "话题"
        verbose_name_plural = verbose_name



    def __str__(self):
        return self.title

# 话题图片
class TopicImg(BaseModel):
    topic = models.ForeignKey(Topic, on_delete=models.CASCADE, verbose_name="话题")
    image = models.ImageField(upload_to="topimg/%Y/%m", null=True, blank=True, verbose_name="话题图片", max_length=200)

    class Meta:
        verbose_name = "话题图片"
        verbose_name_plural = verbose_name

    # 在xadmin中显示图片

    def show_image(self):
        return format_html(
            '<a target="_blank" href="{}"> <img width="42" height="42"  src="{}"/></a>', self.id, self.image.url, )

    show_image.short_description = '图片'

    def __str__(self):
        return self.topic

# 点赞
class Like(BaseModel):
    user = models.ForeignKey(WeChatUser, on_delete=models.CASCADE, verbose_name="用户")
    topic = models.ForeignKey(Topic, on_delete=models.CASCADE,verbose_name="话题")
    is_read = models.BooleanField(default=False,verbose_name="是否已读")
    class Meta:
        verbose_name = "话题点赞"
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.topic

# 评论
class TopicComments(BaseModel):
    user = models.ForeignKey(WeChatUser, on_delete=models.CASCADE, verbose_name="用户")
    topic = models.ForeignKey(Topic, on_delete=models.CASCADE,verbose_name="话题")
    comments = models.TextField(verbose_name="评论内容")
    is_read = models.BooleanField(default=False,verbose_name="是否已读")

    class Meta:
        verbose_name = "话题评论"
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.comments